package com.ruoyi.common.utils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.api.ApiResult;
import com.ruoyi.common.utils.bean.BeanCopyUtil;

import java.util.List;
import java.util.function.Supplier;

public class PageUtil {

    /**
     * 将PageInfo对象泛型中的Po对象转化为Vo对象
     *
     * @param pageInfo PageInfo<Po>对象</>
     * @param <P>      Po类型
     * @param <V>      Vo类型
     * @return
     */
    public static <P, V> PageInfo<V> copyToPageInfoVo(PageInfo<P> pageInfo, Supplier<V> supplier) {
        // 创建Page对象，实际上是一个ArrayList类型的集合
        Page<V> page = new Page<>(pageInfo.getPageNum(), pageInfo.getPageSize());
        page.setTotal(pageInfo.getTotal());
        PageInfo<V> pageInfoVo = new PageInfo<>(page);
        List<V> vList = BeanCopyUtil.copyListProperties(pageInfo.getList(), supplier);
        pageInfoVo.setList(vList);
        return pageInfoVo;
    }

    public static <T> ApiResult<PageInfo<T>> buildApiResultPage(List<T> list) {
        PageInfo<T> pageInfo = new PageInfo<>(list);
        if (list.size() == 0) {
            return new ApiResult<PageInfo<T>>().setCode(-1).setMsg("未查到内容!").setData(null).setCode(-1);
        }
        return new ApiResult<PageInfo<T>>().setData(pageInfo);
    }

    public static <P, V> ApiResult<PageInfo<V>> buildApiResultPage(List<P> list, Class<V> vClass) {
        PageInfo<P> pageInfo = new PageInfo<>(list);
        if (list.size() == 0) {
            return new ApiResult<PageInfo<V>>().setCode(-1).setMsg("未查到内容!").setData(null);
        }
        PageInfo<V> pageInfoVo = PageUtil.copyToPageInfoVo(pageInfo, () -> {
            try {
                return vClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        });
        return new ApiResult<PageInfo<V>>().setData(pageInfoVo);
    }


}
